package com.intel.factorytest.activity;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.StatFs;
import android.os.SystemProperties;
import android.util.Log;
import android.view.Gravity;
import android.view.ViewGroup.LayoutParams;
import android.widget.TextView;

import com.intel.factorytest.R;


public class MicroSD extends Activity{
    
    public static final String TAG = "MicroSD";
    TextView tv;
    private static final String TEST_ITEM = "test_item";
    private float mTotalSize = 0;    
    private float mAvailSize = 0;
    private float mMemoryTotalSize = 0;    
    private float mMemoryAvailSize = 0;
    private float mRamTotalSize = 0;    
    private float mRamFreeSize = 0;
    private float mRamUsedSize = 0;    
    private float mRomTotalSize = 0;    
    private float mRomAvailSize = 0;        
    private String mProduct;
    private String mSdPath = "";
    private static final String TEST_RESULT = "test_result";
    private String mTextString = ""; 
    private Timer mTimer = null;
    private static final int FRESH = 1;
      private static final String TEST_ITEM_RESULT = "test_item_result";
     private boolean is_pass = false;

    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);

        Intent intent = getIntent();
/*        String orientationStr = intent.getStringExtra("sd_orientation");
        int orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
        Log.i("util","orientationStr = " + orientationStr);
        if(orientationStr.equals("SCREEN_ORIENTATION_PORTRAIT")) {
            orientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
            super.setRequestedOrientation(orientation);

        } else if(orientationStr.equals("SCREEN_ORIENTATION_LANDSCAPE")) {
            orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
            super.setRequestedOrientation(orientation);

        }
*/
        tv = new TextView(this);
        mProduct = SystemProperties.get("ro.product.name");
        boolean ismounted = Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED);
        //mTextString = ""; 
        if(!ismounted){
            Log.i(TAG, "getString(R.string.SERVICEMENU_SDCARD_UNAVAILABLE_TXT) = " + getString(R.string.SERVICEMENU_SDCARD_UNAVAILABLE_TXT));
            measureApproximateStorageAndRamAndRomAndCPU(false);    
        }
        else{
            Log.i(TAG, "ismounted =" + ismounted);
            measureApproximateStorageAndRamAndRomAndCPU(true);
        }
        
        
        tv.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
        tv.setGravity(Gravity.CENTER);
        tv.setTextSize(24);
        setContentView(tv);    
        
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_MEDIA_MOUNTED);
        filter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
        filter.addDataScheme("file");
        registerReceiver(plugSDReceiver, filter, "permission.CIT_ALLOW_BROADCAST", null);



            
    }    

    
    final BroadcastReceiver plugSDReceiver =  new BroadcastReceiver() {
         
        @Override
        public void onReceive(Context context, Intent intent) {

            Log.i(TAG, "enter onReceive " + intent.getAction());
            
            if (intent.getAction().equals(Intent.ACTION_MEDIA_MOUNTED))
            {
                mSdPath = intent.getData().getPath();
                measureApproximateStorageAndRamAndRomAndCPU(true);
                    
            }
            else if(intent.getAction().equals(Intent.ACTION_MEDIA_UNMOUNTED))
            {
                measureApproximateStorageAndRamAndRomAndCPU(false);
                
            }
            else
            {}
        }
    };





    Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if(msg.what==FRESH){
                boolean ismounted = Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
                Log.i(TAG, "ismounted " + ismounted);
                if(ismounted) {
                    measureApproximateStorageAndRamAndRomAndCPU(true);
                } else {
                    measureApproximateStorageAndRamAndRomAndCPU(false);
                }
            }

        }
        
    };
    @Override
    protected void onResume() {
        super.onResume();
        mTimer = new Timer();
        mTimer.schedule(new TimerTask(){
            
            @Override
            public void run() {
                mHandler.sendEmptyMessage(FRESH);
            }
            
        },1000, 1000);
    }

    
    @Override
    protected void onDestroy(){
        if(mTimer!=null){
            mTimer.cancel();
        }
        unregisterReceiver(plugSDReceiver);
        super.onDestroy();
    }

    private void setTestResult () {
        Intent intent = new Intent();
        Intent mIntent = getIntent();
        int pos = mIntent.getIntExtra(TEST_ITEM,-1);
        intent.putExtra(TEST_ITEM,pos);
        intent.putExtra(TEST_ITEM_RESULT,is_pass);
        setResult(0, intent);
    }
    @Override
    public void finish() {
        setTestResult (); 
        super.finish();
    }

    private void measureApproximateStorageAndRamAndRomAndCPU(boolean needApproximateStorage) {
         synchronized(this) {
        
            mTextString = "";
            measureApproximateRamAndRomAndCPU();
            if(!needApproximateStorage)
                mTextString = mTextString + getString(R.string.SERVICEMENU_SDCARD_UNAVAILABLE_TXT) + "\n";
            measureApproximateStorage(needApproximateStorage);

            tv.setText(mTextString);
        }
    }

    private void callShellCommand(String cmd){
        Log.e(TAG,"########### cmd ="+cmd);
        try {
            Process p = Runtime.getRuntime().exec(new String[]{"sh","-c",cmd});
            InputStream is = p.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            String tmp = "";
            while((tmp=br.readLine())!=null){
                Log.i("yjc",tmp);
                if(tmp.contains("fat")) {
                    String[] tmpStrs = tmp.split(" ");
                    mSdPath = tmpStrs[1];

                }
            }
            br.close();

            InputStream eis = p.getErrorStream();
            InputStreamReader eisr = new InputStreamReader(eis);
            BufferedReader ebr = new BufferedReader(eisr);

            while((tmp=ebr.readLine())!=null){
                Log.e("yjc",tmp);
            }
            ebr.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    private void measureApproximateStorage(boolean need) {
        if(!need) return;
        StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath());
        Log.i(TAG, Environment.getExternalStorageDirectory().getPath());
        
        // sd card ext
        if(Environment.getExternalStorageDirectory().getPath().equals("/storage/emulated/0")) {
            File file = null;
            
            file = new File("/mnt/sdcard_ext");
            if(file.exists()) {
                stat = new StatFs("/mnt/sdcard_ext");
            } else {
                if(!mSdPath.equals("")) {
                    file = new File(mSdPath);
                    if(file.exists()) {
                        stat = new StatFs(mSdPath);
                    }
                } else {
                    callShellCommand("mount");
                    mSdPath =  "/storage/" + mSdPath.substring(mSdPath.lastIndexOf("/") + 1);
                    file = new File(mSdPath);
                    if(file.exists()) {
                        stat = new StatFs(mSdPath);
                    }
                }
            }
        }
        Log.i(TAG, "mSdPath == " + mSdPath);
        final float blockSize = stat.getBlockSize();
        final float totalBlocks = stat.getBlockCount();
        final float availableBlocks = stat.getAvailableBlocks();

        mTotalSize = totalBlocks * blockSize;
        mAvailSize = availableBlocks * blockSize;

        mTotalSize = mTotalSize/(1024*1024*1024);
        mAvailSize = mAvailSize/(1024*1024);
        if (mTotalSize==0) {
            Log.i(TAG, "mTotalSize == 0");
            //tv.setText(getString(R.string.SERVICEMENU_SDCARD_UNAVAILABLE_TXT));
            mTextString +=     getString(R.string.SERVICEMENU_SDCARD_UNAVAILABLE_TXT);
            return;
        }
        if(mTotalSize == mRomTotalSize) {
            Log.i(TAG, "mTotalSize == mRomTotalSize");
            mTextString +=     getString(R.string.SERVICEMENU_SDCARD_UNAVAILABLE_TXT);
            return;
        }
        is_pass = true;
        if (mAvailSize > 1024) {
            mAvailSize = mAvailSize/(1024);
            //tv.setText("External SD Total size is ="+ mTotalSize +"G AvailSize is ="+mAvailSize+"G");
            mTextString += getString(R.string.SERVICEMENU_SDCARD_TOTALSIZE_TXT) + mTotalSize +"G " + getString(R.string.SERVICEMENU_SDCARD_AVAILSIZE_TXT) + mAvailSize+"G";    
        }else { 
            //tv.setText("External SD Total size is ="+ mTotalSize +"G AvailSize is ="+mAvailSize+"M");
            mTextString += getString(R.string.SERVICEMENU_SDCARD_TOTALSIZE_TXT) + mTotalSize +"G " + getString(R.string.SERVICEMENU_SDCARD_AVAILSIZE_TXT) + mAvailSize + "M";                
        }
        


    }

    private void measureApproximateRamAndRomAndCPU () {
        // Ram
        String strRamPath = "/proc/meminfo";
        try {

            FileReader fr = new FileReader(strRamPath);
            BufferedReader br = new BufferedReader(fr, 8192);
            String memTotal = br.readLine().replace(" ", "");
            String[] memTotals = memTotal.split(":");

            String memFree = br.readLine().replace(" ", "");
            String[] memFrees = memFree.split(":");
            
            mRamTotalSize = (float)Integer.parseInt(memTotals[1].substring(0, memTotals[1].length()-2));    
              mRamFreeSize = (float)Integer.parseInt(memFrees[1].substring(0, memFrees[1].length()-2));;
            mRamUsedSize = mRamTotalSize - mRamFreeSize;
            mTextString +=     getString(R.string.SERVICEMENU_RAM_TOTALSIZE_TXT) + mRamTotalSize/1024f +"M  " + getString(R.string.SERVICEMENU_RAM_FREE_TXT) + mRamFreeSize/1024f +"M " + getString(R.string.SERVICEMENU_RAM_USED_TXT) +  mRamUsedSize/1024f +  "M" + "\n";

            //Log.i("meilianggang", memFrees[0] + "-" + memFrees[1].substring(0, memFrees[1].length()-2));
        } catch(IOException e) {
            e.printStackTrace();
        }

        //Rom
        final StatFs stat = new StatFs(Environment.getDataDirectory().getPath());

        final float blockSize = stat.getBlockSize();
        final float totalBlocks = stat.getBlockCount();
        final float availableBlocks = stat.getAvailableBlocks();

        mRomTotalSize = totalBlocks * blockSize;
        mRomAvailSize = availableBlocks * blockSize;

        mRomTotalSize = mRomTotalSize/(1024*1024*1024);
        mRomAvailSize = mRomAvailSize/(1024*1024);
        if (mTotalSize==0) {        
            
        }
        if (mRomAvailSize > 1024) {
            mRomAvailSize = mRomAvailSize/(1024);
            mTextString += getString(R.string.SERVICEMENU_ROM_TOTALSIZE_TXT) + mRomTotalSize + "G " + getString(R.string.SERVICEMENU_ROM_AVAIL_TXT) + mRomAvailSize + "G" + "\n";    
            //Log.i("meilianggang","total size " + mRomTotalSize + "G" + " avail size " + mRomAvailSize + "G");            
        }else { 
            //Log.i("meilianggang","total size " + mRomTotalSize + "G" + " avail size " + mRomAvailSize + "M");
            mTextString += getString(R.string.SERVICEMENU_ROM_TOTALSIZE_TXT) + mRomTotalSize + "G " + getString(R.string.SERVICEMENU_ROM_AVAIL_TXT) + mRomAvailSize + "M" + "\n";                    
        }


    }

    public boolean ac_ispass() {
        return is_pass;
    } 
}
